package permission

import (
	"errors"
	domain "furniture-server-gin/api/pkg/domain/permission"
)

var (
	ErrPermissionNotFound = errors.New("permission not found")
)

// Service 权限应用服务
type Service struct {
	repo domain.Repository
}

// NewService 创建权限服务
func NewService(repo domain.Repository) *Service {
	return &Service{
		repo: repo,
	}
}

// CreatePermission 创建权限
func (s *Service) CreatePermission(name, description, resource, action string) error {
	// 检查权限是否已存在
	if _, err := s.repo.FindByName(name); err == nil {
		return errors.New("permission already exists")
	}

	// 创建权限
	permission := domain.NewPermission(name, description, resource, action)
	return s.repo.Create(permission)
}

// GetPermissionByID 根据ID获取权限
func (s *Service) GetPermissionByID(id string) (*domain.Permission, error) {
	return s.repo.FindByID(id)
}

// GetPermissionByName 根据名称获取权限
func (s *Service) GetPermissionByName(name string) (*domain.Permission, error) {
	return s.repo.FindByName(name)
}

// GetAllPermissions 获取所有权限
func (s *Service) GetAllPermissions() ([]*domain.Permission, error) {
	return s.repo.FindAll()
}

// UpdatePermission 更新权限
func (s *Service) UpdatePermission(id, name, description, resource, action string) error {
	permission, err := s.repo.FindByID(id)
	if err != nil {
		return ErrPermissionNotFound
	}

	permission.Update(name, description, resource, action)
	return s.repo.Update(permission)
}

// DeletePermission 删除权限
func (s *Service) DeletePermission(id string) error {
	return s.repo.Delete(id)
}
